package controller

import (
	"api/middleware"
	"api/model"
	"api/utils"
	"api/utils/response"
	"fmt"
	"github.com/gin-gonic/gin"
	"net/http"
	"time"
)

/**
 * @Description
 * @Author huan.wang
 * @Date 2021/5/5 8:42 下午
 **/

func UserLogin(ctx *gin.Context) {
	user := model.NewUserModel()
	err := ctx.ShouldBindJSON(&user)
	if err != nil {
		response.ErrorResponse(ctx, model.NewMessageResult(500, err.Error()))
		return
	}
	dbuser := user.SelectByPhone()
	if dbuser.ID != 0 && dbuser.Password == user.Password {
		tokenString, _ := middleware.SetToken(1, dbuser.ID)
		dbuser.LastLoginIp = ctx.ClientIP()
		dbuser.LastLoginTime = time.Now()
		dbuser.Update()
		ctx.JSON(http.StatusOK, model.NewMessageDataResult(200, "登录成功", tokenString))
	} else {
		ctx.JSON(http.StatusOK, model.NewMessageResult(500, "用户名或密码错误"))
	}
}

func UserRegister(ctx *gin.Context) {
	user := model.NewUserModel()
	err := ctx.ShouldBindJSON(&user)
	if err != nil {
		response.ErrorResponse(ctx, model.NewMessageResult(500, err.Error()))
		return
	}
	dbuser := user.SelectByPhone()
	if dbuser.ID != 0 {
		response.SuccessResponse(ctx, model.NewMessageResult(500, "手机号已注册"))
		return
	}
	user.Password = utils.GetStringMd5(user.Password)
	user.Name = "用户" + user.Phone[7:]
	id, err := user.Insert()
	if err != nil {
		response.SuccessResponse(ctx, model.NewMessageResult(500, err.Error()))
		return
	}
	response.SuccessResponse(ctx, model.NewMessageDataResult(200, "注册成功", id))
}

func UserInfo(ctx *gin.Context) {
	uid := ctx.Keys["claims"].(*middleware.Claims).UID
	user := model.NewUserModel()
	user.ID = uid
	dbuser := user.Select()
	if dbuser.ID != 0 {
		var userInfo = map[string]interface{}{
			"id":            dbuser.ID,
			"name":          dbuser.Name,
			"lastLoginIp":   dbuser.LastLoginIp,
			"lastLoginTime": dbuser.LastLoginTime.Format("2006-01-02 15:04:05"),
			"createTime":    dbuser.CreatedAt,
		}
		response.SuccessResponse(ctx, model.NewMessageDataResult(200, "success", userInfo))
	} else {
		response.ErrorResponse(ctx, model.NewMessageResult(500, "用户不存在"))
	}
}

func UserAuth(ctx *gin.Context) {
	uid := ctx.Keys["claims"].(*middleware.Claims).UID
	response.SuccessResponse(ctx, model.NewMessageResult(200, fmt.Sprintf("用户 ID = %d 已认证", uid)))
}
